#include <stdio.h>
#include <sys/types.h> /* See NOTES */
#include <sys/socket.h>
#include <string.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <pthread.h>
#include <sys/ioctl.h>
#include <net/if.h>
int main(int argc, char *argv[])
{
    int sockfd = socket(AF_INET, SOCK_STREAM, 0);

    // 创建Server端地址结构体
    struct sockaddr_in addr;
    addr.sin_family = AF_INET;                        // 使用ipv4
    addr.sin_port = htons(80);                        // 端口   htons()  主机字节序转网络字节序host to net
    addr.sin_addr.s_addr = inet_addr("98.85.20.193"); // ip  inet_addr() 将主机IP 转成 网络IP
    // 只能写 ip 不能写主机名 使用gethostbyname 把主机名转换为ip（DNS）

    int connect_res = connect(sockfd, (struct sockaddr *)&addr, sizeof(addr));

    if (connect_res == -1)
    {
        perror("connect");
        return -1;
    }
    printf("connect success\n");
    char *request = "GET /get HTTP/1.1\r\nHost: httpbin.org\r\nConnection: close\r\n\r\n";
    int send_res = send(sockfd, request, strlen(request), 0);
    if (send_res == -1)
    {
        perror("send");
        return -1;
    }
    printf("send success\n");
    char buf[1024];
    while (1)
    {
        int recv_res = recv(sockfd, buf, 1024, 0);
        if (recv_res == -1)
        {
            perror("recv");
            return -1;
        }
        if (recv_res == 0)
        {
            printf("server close\n");
            break;
        }
        printf("recv: %s\n", buf);
    }

    return 0;
}